<?php
/**
 * Created by PhpStorm.
 * User: LENOVO
 * Date: 2018/8/14
 * Time: 23:44
 */

namespace app\api\controller;


use app\api\model\WxUser;
use app\wx\WxConfig;

class Wx extends WxConfig
{
  public function wxLogin()
  {
    $redirectUrl = "http://www.linqinghu.cn/ruixiang//user/userCenter.html?nickname=%s&headimgurl=%s";
    $code = input('code');
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appId&secret=$this->appSecret&code={$code}&grant_type=authorization_code";
    $wxResult = $this->_request('get', $url);
    $wxResult2 = json_decode($wxResult, true);
    $openid = $wxResult2['openid'];
    $user_info_result_array = $this->getUserInfo($openid);

    //可以打印测试看数据
    //return json_encode($user_info_result_array);

    return redirect(sprintf($redirectUrl, $user_info_result_array['nickname'], $user_info_result_array['headimgurl']));
  }

  protected function getUserInfo($openid)
  {
    $wxUserModel = new WxUser();
    $result = $wxUserModel::where('openid', $openid)->find();
    if (!$result) {
      //如果没有就新增插入
      $access_token = $this->getWxAccessToken();
      $get_user_info_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
      $user_info_result_array = json_decode($this->_request('get', $get_user_info_url), true);
      $user_info_result_array['uid'] = null;
      $saveResult = $wxUserModel->save($user_info_result_array);
      if ($saveResult) {
        return $user_info_result_array;
      }
    } else {
      return json_decode($result, true);
    }
  }
}